<template>
  <div class="layout"
    :style="{
      'background-color': bigScreenStyle.backgroundColor,
    }"
  >
    <div v-zoom.fixed="transformInfo" v-drag="transformInfo" class="img-wrapper" :class="{ isHandled: isHandled }"
      style="transform: scale(0.8);left: -170px;top: 20px;"
      :style="{
        transform: 'scale('+transformInfo.scale+')',
        left: transformInfo.positionLeft + 'px',
        top: transformInfo.positionTop + 'px',
        width: transformInfo.containerWidth + 'px',
        height: transformInfo.containerHeight + 'px'
      }">
      <!-- 工艺图底图 -->
      <img src="" class="base-img">
      <!-- 构件 -->
      <widget
        v-for="(widget, index) in widgets" :key="index" v-model="widget.value" :index="index"
        :type="widget.type" :ispreview="true"></widget>
    </div>
  </div>

</template>

<script>
  import widget from "../designer/widget/temp";
  import {
    detailDashboard
  } from "@/api/bigscreen";
  export default {
    name: "Login",
    components: {
      widget
    },
    data() {
      return {
        bigScreenStyle: {},
        widgets: [],
        dashboardData: {},
        baseImgNode: null, // 工艺底图DOM对象
        baseImgWidth: 0, // 工艺底图原始宽
        baseImgHeight: 0, // 工艺底图原始高
        initProperty: {
          scale: 1, // 图片初始放大倍数
          positionLeft: 0, // 初始 css position left
          positionTop: 0, // 初始 css position top
        },

        transformInfo: {
          containerWidth: 1920, // 画布宽度，取决于工艺底图尺寸
          containerHeight: 1080, // 根据工艺底图宽高比例，计算得出
          positionLeft: 0, // 实时 css position left
          positionTop: 0, // 实时 css position top
          scale: 0, // 图片实时放大倍数
          maxZoomScale: 3, // 图片最大放大倍数
          minZoomScale: 0.2, // 图片最小放大倍数
          zoomScaleOffset: 0.1, // 鼠标滚轮每次滚动时图片放大倍数变化量
        }
      };
    },
    computed: {
      // 是否对工艺图进行了操作【缩放，平移】
      isHandled() {
        return this.transformInfo.scale !== this.initProperty.scale || this.transformInfo.positionLeft !== this.initProperty
          .positionLeft || this.transformInfo.positionTop !== this.initProperty.positionTop
      },
    },
    mounted() {
      // let {
      //   left,
      //   top,
      //   transform
      // } = document.querySelector('.img-wrapper').style
      // // 正则捕获scale倍数值，先行断言'scale('，后行断言')'，反斜线'\'转义圆括号
      // let scaleMatchObj = new RegExp(/(?<=scale\()(\d+\.)?\d+(?=\))/).exec(transform)
      // if (scaleMatchObj === null) {
      //   this.initProperty.scale = 1
      // } else {
      //   // this.initProperty.scale = Number(scaleMatchObj[0])
      //   this.initProperty.scale = 1
      // }
      // let [pleft, ptop] = [parseFloat(left), parseFloat(top)]
      // this.initProperty.positionLeft = isNaN(pleft) ? 0 : pleft
      // this.initProperty.positionTop = isNaN(ptop) ? 0 : ptop

      this.getData();
    },
    methods: {
      async getData() {
        const reportCode = this.$route.query.reportCode;
        const {
          code,
          data
        } = await detailDashboard(reportCode);
        if (code != 200) return;
        this.dashboardData = data.dashboard
        const equipment = document.body.clientWidth;
        const ratioEquipment = equipment / data.dashboard.width;
        this.bigScreenStyle = {
          // width: data.dashboard.width + "px",
          // height: data.dashboard.height + "px",
          "backgroundColor": data.dashboard.backgroundColor,
          // "background-image": "url(" + data.dashboard.backgroundImage + ")",
          // "background-position": "0% 0%",
          // "background-size": "100% 100%",
          // "background-repeat": "initial",
          // "background-attachment": "initial",
          // "background-origin": "initial",
          // "background-clip": "initial",
          // transform: `scale(${ratioEquipment}, ${ratioEquipment})`,
          // "transform-origin": "0 0"
        };
        this.transformInfo.containerWidth = data.dashboard.width
        this.transformInfo.containerHeight = data.dashboard.height
        // 重置
        this.resetZoomAndPosition()
        // 初始化
        this.baseImgNode = document.querySelector('.img-wrapper .base-img')
        this.baseImgNode.src = data.dashboard.backgroundImage

        this.$nextTick(() => {
          // 放置构件
          data.dashboard.widgets.forEach((item, index) => {
            item.value.widgetId = item.value.setup.widgetId
            item.value.widgetCode = item.value.setup.widgetCode
            if (item.value.setup.componentLinkage && item.value.setup.componentLinkage.length) {
              this.$store.commit('SET_ALL_COMPONENT_LINKAGE', {
                index,
                widgetId: item.value.widgetId,
                linkageArr: item.value.setup.componentLinkage
              })
            }
          })
          this.widgets = data.dashboard.widgets;
        })

      },

      zoom(offset) {
        this.transformInfo.scale = Number((this.transformInfo.scale + offset).toFixed(2))
      },
      resetZoomAndPosition() {
        for (let k in this.initProperty) {
          this.transformInfo[k] = this.initProperty[k]
        }
        // 重新设置left top scale
        // this.transformInfo.scale = (this.dashboardData.initialScale || 100) / 100
        // this.transformInfo.positionLeft = this.dashboardData.initialLeft
        // this.transformInfo.positionTop = this.dashboardData.initialTop
      },
    },
    directives: {
      zoom: {
        bind(el, binding) {
          // 是否定点缩放
          const isFixed = Reflect.has(binding.modifiers, 'fixed')
          // 变化量
          let [mutationX, mutationY] = [0, 0]

          el.addEventListener('mousewheel', (evt) => {

            if (isFixed) {
              const rect = el.getBoundingClientRect()

              const [unitOffsetX, unitOffsetY] = [binding.value.containerWidth * 0.5 * binding.value
                .zoomScaleOffset, binding.value.containerHeight * 0.5 * binding.value.zoomScaleOffset
              ]
              // 图片左边缘到浏览器可视区域左边缘距离、图片上边缘到浏览器可视区域上边缘距离
              let [whiteDistanceX, whiteDistanceY] = [rect.left, rect.top]
              // 图片中心点到图片左边缘、上边缘距离
              let [centerImgDistanceX, centerImgDistanceY] = [binding.value.containerWidth * binding.value.scale *
                0.5, binding.value.containerHeight * binding.value.scale * 0.5
              ]
              // 光标到图片左边缘、上边缘距离
              let [mouseImgDistanceX, mouseImgDistanceY] = [evt.x - whiteDistanceX, evt.y -
                whiteDistanceY
              ]

              mutationX = +Number((centerImgDistanceX - mouseImgDistanceX) / centerImgDistanceX *
                unitOffsetX).toFixed(2)
              mutationY = +Number((centerImgDistanceY - mouseImgDistanceY) / centerImgDistanceY *
                unitOffsetY).toFixed(2)
            }

            if (evt.wheelDelta > 0) {
              // 图片放大
              if (binding.value.scale >= binding.value.maxZoomScale) {
                return
              }

              binding.value.positionLeft += mutationX
              binding.value.positionTop += mutationY
              binding.value.scale = Number((binding.value.scale + binding.value.zoomScaleOffset).toFixed(2))

            } else {
              // 图片缩小
              if (binding.value.scale <= binding.value.minZoomScale) {
                return
              }
              binding.value.positionLeft -= mutationX
              binding.value.positionTop -= mutationY
              binding.value.scale = Number((binding.value.scale - binding.value.zoomScaleOffset).toFixed(2))
            }

          })
        },
      },
      drag: {
        bind(el, binding) {
          el.onmousedown = function(downEvent) {
            downEvent.stopPropagation()

            let [prevX, prevY] = [downEvent.x, downEvent.y]

            document.onmousemove = function(moveEvent) {
              binding.value.positionLeft += moveEvent.x - prevX;
              binding.value.positionTop += moveEvent.y - prevY;
              [prevX, prevY] = [moveEvent.x, moveEvent.y]
            }

            // 鼠标停止移动时，事件移除
            document.onmouseup = function(e) {
              document.onmousemove = null
              document.onmouseup = null
            }

          }

        }
      }
    },
  };
</script>

<style scoped lang="scss">

  .layout {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .base-img {
    width: 100%;
    height: 100%;
  }

  .img-wrapper {
    position: absolute;
    user-select: none;
    z-index: 1;
  }

  .img-wrapper img {
    pointer-events: none;
    /* pointer-events: unset; */
  }

  .bottom-text {
    width: 100%;
    color: #a0a0a0;
    position: fixed;
    bottom: 16px;
    z-index: 9999;
  }
</style>
